package com.example.demo.utils;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


public class DESUtil {

    private final static String DES = "DES";

    private static SecureRandom sr;

    // 密钥，长度必须是8的倍数
    private static final String KEY = "QWERTYUIOPASDFG";
    static {
        sr = new SecureRandom();
    }
    /**
     * 加密
     * @param src  数据源
     * @param key 密钥，长度必须是8的倍数
     */
    private static byte[] encrypt(byte[] src, byte[] key) throws Exception {
        SecretKey secureKey = getSecretKey(key);
        Cipher cipher = Cipher.getInstance(DES);
        cipher.init(Cipher.ENCRYPT_MODE, secureKey, sr);
        return cipher.doFinal(src);
    }

    /** 加密
     * @param data  2015-11-15
     * @return String
     */
    public static String encrypt(String data) {
        if (data != null)
            try {
                return byte2hex(encrypt(data.getBytes(), KEY.getBytes()));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        return null;
    }

    /**
     * 解密
     * @param src 数据源
     * @param key 密钥，长度必须是8的倍数
     * @return 返回解密后的原始数据
     */
    private static byte[] decrypt(byte[] src, byte[] key) throws Exception {
        SecretKey secureKey = getSecretKey(key);
        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, secureKey, sr);
        return cipher.doFinal(src);
    }

    private static SecretKey getSecretKey(byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
        SecureRandom sr = new SecureRandom();
        DESKeySpec dks = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        return keyFactory.generateSecret(dks);
    }


    /**
     * 解密
     * @return 返回解密后的原始数据
     */
    public static String decrypt(String data) throws Exception {
        return new String(decrypt(hex2byte(data.getBytes()), KEY.getBytes())).trim();
    }

    private static String byte2hex(byte[] b) {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }

    private static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0)
            throw new IllegalArgumentException();
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }
}
